﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using S.Common.EditWanderStateHelper;
using S.Common.helper;
using S.Transplantation.Api.Application.Command;
using S.Transplantation.Domain.Models;
using S.Transplantation.Infrastructure.InterFace;
using S.Transplantation.Read.Api.Dto;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Net.Http.Headers;
using System.Net.Http;
using Consul;
using System.Collections.Generic;

namespace S.Transplantation.Api.Application.CommandHandlers
{
    public class TransplantationCommandHandler :
        IRequestHandler<UpdateTransplantationListCommand, int>,
        IRequestHandler<AddTransplantationListCommand, int>,
        IRequestHandler<DeleteTransplantationListCommand, int>
    {
        private readonly IDescendantTransfertRepository DTRepository;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IConfiguration configuration;
         

        public TransplantationCommandHandler(IDescendantTransfertRepository DTRepository, IMapper mapper, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.DTRepository = DTRepository;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }

       
        /// <summary>
        /// 批量修改后裔转种
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(UpdateTransplantationListCommand request, CancellationToken cancellationToken)
        {
            string Gateway = configuration.GetValue<string>("Gateway");
            foreach (var item in request.UpdatetransplantationListDtos)
            {
                //查询转舍记录最新信息
                SheepRescission reqult = HttpClientHelper.GetResponse<SheepRescission>(Gateway + $"/transferset/api/SheepFrom/GetSheepFromByDate?EarTag={item.EarTag}");
                ////如果最新信息时间大于转舍时间,不能删除
                DateTime? zhaunshedate = reqult.SurrenderDate;
                if(item.TransferDate> zhaunshedate)
                {
                    return -1;
                }
                else
                {
                    //修改转舍记录
                    TransFerUpdateCommand transFer = new TransFerUpdateCommand()
                    {
                        SheepRescissionId = reqult.SheepRescissionId,
                        ShiftToBuild = Convert.ToInt32(item.ShiftToHuts),
                        ShiftToBuildingManagementId= Convert.ToInt32(item.ShiftToHuts),
                        ShiftToColumnManagementId= Convert.ToInt32(item.ShiftToBuild),
                        ShiftToHuts= Convert.ToInt32(item.ShiftToBuild),

                    };
                    HttpClientHelper.PutDataResponse(Gateway + $"/transset/api/TransFer/UpdateSheepTransFers", transFer);

                }
            }
            //var descendantTransferModels = mapper.Map<List<DescendantTransferModel>>(request.UpdatetransplantationListDtos);
            var descendantTransferModels = DTRepository.GetAll().FirstOrDefault(x => x.DescendantTransferId == request.UpdatetransplantationListDtos.FirstOrDefault().DescendantTransferId);

           

                // 修改部分字段
               
            descendantTransferModels.ShiftToHuts = request.UpdatetransplantationListDtos.FirstOrDefault().ShiftToHuts;
            descendantTransferModels.ShiftToBuild = request.UpdatetransplantationListDtos.FirstOrDefault().ShiftToBuild;
            descendantTransferModels.UpdateBy = request.UpdatetransplantationListDtos.FirstOrDefault().UpdateBy;
            descendantTransferModels.UpdateDate = DateTime.Now;




            var t=  await DTRepository.UpdateAsync(descendantTransferModels);
            if (t)
            {
                return 1;
            }
            else
            {
                return 0;
            }
           
        }
        public class TransFerUpdateCommand
        {
            public int SheepRescissionId { get; set; }
            /// <summary>
            /// 转入栋舍
            /// </summary>
            public int ShiftToBuild { get; set; }
            /// <summary>
            /// 转入栏位
            /// </summary>
            public int ShiftToHuts { get; set; }
            /// <summary>
            /// 转入栋舍主键
            /// </summary>
            public int ShiftToBuildingManagementId { get; set; }
            /// <summary>
            /// 转入栏位主键
            /// </summary>
            public int ShiftToColumnManagementId { get; set; }
            /// <summary>
            /// 修改人
            /// </summary>
            public string? UpdateBy { get; set; }
        }

        public async Task<int> Handle(AddTransplantationListCommand request, CancellationToken cancellationToken)
        {
           
            string Gateway= configuration.GetValue<string>("Gateway");

            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer "))
            {
                authHeader = authHeader.Substring("Bearer ".Length).Trim();
            }

            List<string> eartag = new List<string>();
            Transfer sheep = new Transfer();
            foreach (var item in request.AddtransplantationListDtos)
            {

                eartag.Add(item.EarTag);
                item.CreateDate = DateTime.Now;
              
                item.UpdateBy = "";
                item.TransferDate = item.TransferDate;
                if (string.IsNullOrEmpty(item.TurnOutHuts)|| string.IsNullOrEmpty(item.TurnOutBuild))
                {
                    // 批量添加转舍记录
                    TransferRecords transfer = new TransferRecords()
                    {
                        EarTag = item.EarTag,
                        SurrenderDate = item.TransferDate,
                        RoundType = 12,
                        TurnOutBuild = 0,
                        TurnOuBuildingManagementId = 0,
                        //转出栏位 //当前栏位
                        TurnOutHuts = 0,
                        TurnOuColumnManagementId = 0,
                        //转入栋舍
                        ShiftToBuild = Convert.ToInt32(item.ShiftToHuts),
                        ShiftToBuildingManagementId = Convert.ToInt32(item.ShiftToHuts),
                        //转入栏位
                        ShiftToHuts = Convert.ToInt32(item.ShiftToBuild),
                        ShiftToColumnManagementId = Convert.ToInt32(item.ShiftToBuild),
                        Variety = "",
                        CreateBy = item.CreateBy,
                        CreateDate = DateTime.Now,
                        DocumentNumbe = Convert.ToInt64(item.DocumentNumber),

                    };
                    sheep.sheep.Add(transfer);
                }
                else
                {
                    // 批量添加转舍记录
                    TransferRecords transfer = new TransferRecords()
                    {
                        EarTag = item.EarTag,
                        SurrenderDate = item.TransferDate,
                        RoundType = 12,
                        TurnOutBuild = Convert.ToInt32(item.TurnOutHuts),
                        TurnOuBuildingManagementId = Convert.ToInt32(item.TurnOutHuts),
                        //转出栏位 //当前栏位
                        TurnOutHuts = Convert.ToInt32(item.TurnOutBuild),
                        TurnOuColumnManagementId = Convert.ToInt32(item.TurnOutBuild),
                        //转入栋舍
                        ShiftToBuild = Convert.ToInt32(item.ShiftToHuts),
                        ShiftToBuildingManagementId = Convert.ToInt32(item.ShiftToHuts),
                        //转入栏位
                        ShiftToHuts = Convert.ToInt32(item.ShiftToBuild),
                        ShiftToColumnManagementId = Convert.ToInt32(item.ShiftToBuild),
                        Variety = "",
                        CreateBy = item.CreateBy,
                        CreateDate = DateTime.Now,
                        DocumentNumbe = Convert.ToInt64(item.DocumentNumber),
                    };
                       sheep.sheep.Add(transfer);
                }
            }

            int a = await DTRepository.AddRangeAsync(mapper.Map<List<DescendantTransferModel>>(request.AddtransplantationListDtos));
            if (a > 0)
            {
                //修改羊只档案类型
                var i = HttpClientHelper.PutDataResponse(Gateway+"/achs/api/SheepFileModel/TransplantStateEditPL", eartag);
                //修改流转状态
                var j = EditWanderState.EditWanderPL(eartag, 6, Gateway);

                //批量转舍
                var z = HttpClientHelper.PostResponseKey(Gateway+ "/transset/api/TransFer/CreateSheepTransFers", sheep);
                //批量添加生产记录
            }
            return a;
        }
        /// <summary>
        /// 批量删除羊转种
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(DeleteTransplantationListCommand request, CancellationToken cancellationToken)
        {
          
            string Gateway = configuration.GetValue<string>("Gateway");

            string[] idArray = request.Ids.Split(",");
            List<int> ints = idArray.Select(int.Parse).ToList();

            var list = DTRepository.GetAllAsync().Result.Where(a => ints.Contains(a.DescendantTransferId));
          
            //判断转种转舍之后,是否有其他转舍
            foreach (var item in list)
            {
                var id = item.DescendantTransferId;
                var date = item.TransferDate;
                //查询转舍记录最新信息
                SheepRescission reqult = HttpClientHelper.GetResponse<SheepRescission>(Gateway+ $"/transferset/api/SheepFrom/GetSheepFromByDate?EarTag={item.EarTag}");
                ////如果最新信息时间大于转舍时间,不能删除
                DateTime? zhaunshedate = reqult.SurrenderDate;
                if (zhaunshedate > date)
                {
                    return -1;
                }
                //否则可以删除
                else
                {
                   // 修改流转状态
                    var j = EditWanderState.EditWander(item.EarTag, 5, Gateway);
                    //修改羊只档案类型
                    var k = HttpClientHelper.PostResponse(Gateway+$"/achs/api/SheepFileModel/SheepFileEdit?EarTag={item.EarTag}", "");
                    //删除转舍记录
                    var datetime = item.TransferDate.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
                    var d = HttpClientHelper.DeleteResponse(Gateway+ $"/transset/api/TransFer/DeleteSheepTransFer?EarTag={item.EarTag}&SurrenderDate={datetime}");
                }

            }
          
            int a = DTRepository.RemoveRange(list);

            return a;
        }
    }
    //批量添加转舍记录
    public class Transfer
    {
        public List<TransferRecords> sheep { get; set; }

        public Transfer()
        {
            sheep = new List<TransferRecords>();
        }
    }

    public class TransferRecords
    {
        /// <summary>
        /// 转舍主键，自增标识列
        /// </summary>
        public int SheepRescissionId { get; set; }
        /// <summary>
        /// 可视耳标
        /// </summary>
        public string? EarTag { get; set; }
        /// <summary>
        /// 转舍日期
        /// </summary>
        public DateTime? SurrenderDate { get; set; }
        /// <summary>
        /// 转舍类型
        /// </summary>
        public int RoundType { get; set; }
        /// <summary>
        /// 转出栋舍
        /// </summary>
        public int? TurnOutBuild { get; set; }

        /// <summary>
        /// 转出栏位
        /// </summary>
        public int? TurnOutHuts { get; set; }
        /// <summary>
        /// 转出栋舍主键
        /// </summary>
        public int? TurnOuBuildingManagementId { get; set; }
        /// <summary>
        /// 转出栏位主键
        /// </summary>
        public int? TurnOuColumnManagementId { get; set; }
        /// <summary>
        /// 转入栋舍
        /// </summary>
        public int ShiftToBuild { get; set; }
        /// <summary>
        /// 转入栏位
        /// </summary>
        public int ShiftToHuts { get; set; }
        /// <summary>
        /// 转入栋舍主键
        /// </summary>
        public int ShiftToBuildingManagementId { get; set; }
        /// <summary>
        /// 转入栏位主键
        /// </summary>
        public int ShiftToColumnManagementId { get; set; }
        /// <summary>
        /// 品种
        /// </summary>
        public string? Variety { get; set; }
        /// <summary>
        /// 创建人
        /// </summary>
        [Column(TypeName = "nvarchar(20)")]
        [MaxLength(20)]
        public string? CreateBy { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime? CreateDate { get; set; }

        /// <summary>
        /// 修改人
        /// </summary>
        [Column(TypeName = "nvarchar(20)")]
        [MaxLength(20)]
        public string? UpdateBy { get; set; }

        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime? UpdateDate { get; set; }
        /// <summary>
        /// 是否删除
        /// </summary>
        public bool IsDel { get; set; }
        /// <summary>
        /// 单据号
        /// </summary>
        public long DocumentNumbe { get; set; }
        /// <summary>
        /// 羊只类型
        /// </summary>
        public string? Type { get; set; }
    }
    /// <summary>
    /// 羊只转舍
    /// </summary>
    public class SheepRescission
    {
        /// <summary>
        /// 转舍主键，自增标识列
        /// </summary>
        [Key]
        public int SheepRescissionId { get; set; }
        /// <summary>
        /// 可视耳标
        /// </summary>
        public string? EarTag { get; set; }
        /// <summary>
        /// 转舍日期
        /// </summary>
        public DateTime? SurrenderDate { get; set; }
        /// <summary>
        /// 转舍类型
        /// </summary>
        public int RoundType { get; set; }
        /// <summary>
        /// 转出栋舍
        /// </summary>
        public int TurnOutBuild { get; set; }
        /// <summary>
        /// 转出栏位
        /// </summary>
        public int TurnOutHuts { get; set; }
        /// <summary>
        /// 转出栋舍主键
        /// </summary>
        public int TurnOuBuildingManagementId { get; set; }
        /// <summary>
        /// 转出栏位主键
        /// </summary>
        public int TurnOuColumnManagementId { get; set; }
        /// <summary>
        /// 转入栋舍
        /// </summary>
        public int ShiftToBuild { get; set; }
        /// <summary>
        /// 转入栏位
        /// </summary>
        public int ShiftToHuts { get; set; }
        /// <summary>
        /// 转入栋舍主键
        /// </summary>
        public int ShiftToBuildingManagementId { get; set; }
        /// <summary>
        /// 转入栏位主键
        /// </summary>
        public int ShiftToColumnManagementId { get; set; }
        /// <summary>
        /// /// <summary>
        /// 品种
        /// </summary>
        public int? Variety { get; set; }
        /// 创建人
        /// </summary>
        [Column(TypeName = "nvarchar(20)")]
        [MaxLength(20)]
        public string? CreateBy { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime? CreateDate { get; set; }
        /// <summary>
        /// 修改人
        /// </summary>
        [Column(TypeName = "nvarchar(20)")]
        [MaxLength(20)]
        public string? UpdateBy { get; set; }
        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime? UpdateDate { get; set; }
        /// <summary>
        /// 是否删除
        /// </summary>
        public bool IsDel { get; set; }
        /// <summary>
        /// 单据号
        /// </summary>
        public long DocumentNumbe { get; set; }
        /// <summary>
        /// 羊只类型
        /// </summary>
        public string? Type { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public int Sex { get; set; }

    }
}